#include "stdafx.h"
#include "LuaMemory.h"
//#include <unistd.h>
#include<comutil.h>
#include <comdef.h>

static int luaReadNumber(lua_State* L)
{
	DWORD d = (DWORD)lua_tointeger(L,1);
	DWORD s = (DWORD)lua_tointeger(L,2);
	DWORD r = 0;
	switch(s)
	{
	case 2:                           
		r = *((unsigned short*)d);
		break;
	case 1:
		r = *((unsigned char*)d);
		break;
	case 4:
	default:
		r = *((unsigned int*)d);
	}
	lua_pushnumber(L,r);
	return 1;  /* new userdatum is already on the stack */ 
}

static int luaReadUnicodeString(lua_State* L)
{
	DWORD addr = (DWORD)lua_tointeger(L,1);
	DWORD size = (DWORD)lua_tointeger(L,2);
	wchar_t* pTarget = (wchar_t*)addr;
	_bstr_t t(pTarget);
	char* r = (char*)t;
	lua_pushstring(L,r);
	return 1;
}

static int luaReadAsciiString(lua_State* L)
{
	DWORD addr=(DWORD)lua_tointeger(L,1);
	DWORD size=(DWORD)lua_tointeger(L,2);
	char* pTarget=(char*)addr;
	_bstr_t t(pTarget);
	char* r=(char*)r;
	lua_pushstring(L,r);
	return 1;
}






//////////////////////////////////////////////////////////////////////////
static const struct luaL_reg memoryLib [] = { 
	{"ReadNumber", luaReadNumber}, 
	{"ReadUnicodeString", luaReadUnicodeString}, 
	{"ReadAsciiString", luaReadAsciiString}, 
	{NULL, NULL} 
};
bool OpenLuaMemory(lua_State* lua)
{
	luaI_openlib(lua,"Memory",memoryLib,1);
	return true;
}
